package com.imut.lagain.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.imut.lagain.entity.HealthReminder;
import com.imut.lagain.service.IPeriodCareService;
import com.imut.lagain.service.IHealthReminderService;
import com.imut.lagain.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生理期关怀服务实现类
 */
@Service
@RequiredArgsConstructor
public class PeriodCareServiceImpl implements IPeriodCareService {
    private static final Logger log = LoggerFactory.getLogger(PeriodCareServiceImpl.class);

    
    private final IHealthReminderService healthReminderService;
    private final IUserService userService;
    private static final String CARE_TYPE_COMFORT = "comfort"; // 安慰关怀
    private static final String CARE_TYPE_NUTRITION = "nutrition"; // 营养关怀
    private static final String CARE_TYPE_EXERCISE = "exercise"; // 运动关怀
    private static final String CARE_TYPE_EMOTIONAL = "emotional"; // 情感关怀
    private static final String CARE_TYPE_PRACTICAL = "practical"; // 实用关怀
    
    @Override
    public boolean createCareReminder(Long userId, Long partnerId, String careType, String message, LocalDateTime remindTime) {
        try {
            HealthReminder reminder = new HealthReminder();
            reminder.setUserId(partnerId); // 提醒发送给伴侣
            reminder.setReminderType("CARE");
            reminder.setRemindTime(remindTime);
            reminder.setMessage(String.format("[%s关怀] %s", getCareTypeName(careType), message));
            reminder.setIsCompleted(false);
            
            return healthReminderService.save(reminder);
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public boolean sendCareMessage(Long fromUserId, Long toUserId, String careType, String message) {
        try {
            HealthReminder careMessage = new HealthReminder();
            careMessage.setUserId(toUserId);
            careMessage.setReminderType("CARE");
            careMessage.setRemindTime(LocalDateTime.now());
            careMessage.setMessage(String.format("来自伴侣的%s关怀：%s", getCareTypeName(careType), message));
            careMessage.setIsCompleted(false);
            
            return healthReminderService.save(careMessage);
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Map<String, String>> getCareRecommendations(Long userId, String currentPhase) {
        List<Map<String, String>> recommendations = new ArrayList<>();
        
        switch (currentPhase.toLowerCase()) {
            case "menstrual":
                recommendations.add(createRecommendation(CARE_TYPE_COMFORT, "准备热水袋", "为她准备一个温暖的热水袋，缓解腹部不适"));
                recommendations.add(createRecommendation(CARE_TYPE_NUTRITION, "煮红糖姜茶", "煮一杯温暖的红糖姜茶，补充能量和温暖身体"));
                recommendations.add(createRecommendation(CARE_TYPE_EMOTIONAL, "温柔陪伴", "给她更多的拥抱和理解，情绪可能会比较敏感"));
                recommendations.add(createRecommendation(CARE_TYPE_PRACTICAL, "准备卫生用品", "确保卫生用品充足，贴心准备她需要的物品"));
                break;
            case "follicular":
                recommendations.add(createRecommendation(CARE_TYPE_EXERCISE, "一起运动", "邀请她一起做运动，这是精力充沛的好时期"));
                recommendations.add(createRecommendation(CARE_TYPE_NUTRITION, "营养搭配", "准备富含维生素的新鲜蔬果，支持身体恢复"));
                recommendations.add(createRecommendation(CARE_TYPE_EMOTIONAL, "支持计划", "支持她制定新的计划和目标，给予鼓励"));
                recommendations.add(createRecommendation(CARE_TYPE_PRACTICAL, "安排约会", "安排一些有趣的活动或约会，享受美好时光"));
                break;
            case "ovulation":
                recommendations.add(createRecommendation(CARE_TYPE_EMOTIONAL, "浪漫时光", "安排浪漫的约会，这是感情升温的好时机"));
                recommendations.add(createRecommendation(CARE_TYPE_NUTRITION, "均衡饮食", "准备营养均衡的美食，保持身体最佳状态"));
                recommendations.add(createRecommendation(CARE_TYPE_COMFORT, "护肤关怀", "准备护肤产品，皮肤状态较好适合护理"));
                recommendations.add(createRecommendation(CARE_TYPE_PRACTICAL, "社交支持", "支持她的社交活动，给她更多自由空间"));
                break;
            case "luteal":
                recommendations.add(createRecommendation(CARE_TYPE_EMOTIONAL, "情绪支持", "给予更多耐心和理解，情绪可能会有波动"));
                recommendations.add(createRecommendation(CARE_TYPE_NUTRITION, "控制甜食", "准备健康零食，帮助控制对甜食的渴望"));
                recommendations.add(createRecommendation(CARE_TYPE_COMFORT, "放松活动", "安排放松的活动，如泡澡、按摩等"));
                recommendations.add(createRecommendation(CARE_TYPE_PRACTICAL, "减少压力", "主动承担更多家务，减轻她的压力"));
                break;
            default:
                recommendations.add(createRecommendation(CARE_TYPE_EMOTIONAL, "日常关怀", "保持日常的关心和爱护，让她感受到你的爱"));
        }
        
        return recommendations;
    }
    
    @Override
    public boolean syncPeriodStatus(Long userId, Long partnerId, Map<String, Object> phaseInfo) {
        try {
            String phase = (String) phaseInfo.get("phase");
            Long dayInCycle = (Long) phaseInfo.get("dayInCycle");
            Long daysUntilNext = (Long) phaseInfo.get("daysUntilNext");
            
            String statusMessage = String.format(
                "伴侣生理期状态更新：当前处于%s阶段，周期第%d天，距离下次月经还有%d天",
                getPhaseDisplayName(phase), dayInCycle, daysUntilNext
            );
            
            HealthReminder statusSync = new HealthReminder();
            statusSync.setUserId(partnerId);
            statusSync.setReminderType("PERIOD_STATUS");
            statusSync.setRemindTime(LocalDateTime.now());
            statusSync.setMessage(statusMessage);
            statusSync.setIsCompleted(false);
            
            return healthReminderService.save(statusSync);
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getCareTasks(Long userId, String currentPhase) {
        List<Map<String, Object>> tasks = new ArrayList<>();
        
        switch (currentPhase.toLowerCase()) {
            case "menstrual":
                tasks.add(createCareTask("comfort_1", "准备热水袋", "为伴侣准备温暖的热水袋", CARE_TYPE_COMFORT, 1));
                tasks.add(createCareTask("nutrition_1", "煮红糖水", "煮一杯温暖的红糖水", CARE_TYPE_NUTRITION, 1));
                tasks.add(createCareTask("emotional_1", "温柔陪伴", "给予更多拥抱和理解", CARE_TYPE_EMOTIONAL, 2));
                tasks.add(createCareTask("practical_1", "准备用品", "检查并准备卫生用品", CARE_TYPE_PRACTICAL, 1));
                break;
            case "follicular":
                tasks.add(createCareTask("exercise_1", "运动邀请", "邀请伴侣一起运动", CARE_TYPE_EXERCISE, 2));
                tasks.add(createCareTask("nutrition_2", "营养餐", "准备营养丰富的餐食", CARE_TYPE_NUTRITION, 2));
                tasks.add(createCareTask("emotional_2", "支持计划", "支持伴侣的新计划", CARE_TYPE_EMOTIONAL, 1));
                break;
            case "ovulation":
                tasks.add(createCareTask("emotional_3", "浪漫约会", "安排浪漫的约会", CARE_TYPE_EMOTIONAL, 3));
                tasks.add(createCareTask("comfort_2", "护肤关怀", "准备护肤用品", CARE_TYPE_COMFORT, 1));
                tasks.add(createCareTask("practical_2", "社交支持", "支持伴侣的社交活动", CARE_TYPE_PRACTICAL, 1));
                break;
            case "luteal":
                tasks.add(createCareTask("emotional_4", "情绪支持", "给予耐心和理解", CARE_TYPE_EMOTIONAL, 3));
                tasks.add(createCareTask("comfort_3", "放松活动", "安排放松的活动", CARE_TYPE_COMFORT, 2));
                tasks.add(createCareTask("practical_3", "减少压力", "主动承担家务", CARE_TYPE_PRACTICAL, 2));
                break;
        }
        
        return tasks;
    }
    
    @Override
    public boolean completeCareTask(Long userId, String taskId, Long completedBy) {
        try {
            HealthReminder taskCompletion = new HealthReminder();
            taskCompletion.setUserId(userId);
            taskCompletion.setReminderType("TASK_COMPLETED");
            taskCompletion.setRemindTime(LocalDateTime.now());
            taskCompletion.setMessage(String.format("关怀任务已完成：%s", taskId));
            taskCompletion.setIsCompleted(true);
            
            return healthReminderService.save(taskCompletion);
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getCareHistory(Long userId, int days) {
        try {
            LocalDateTime startTime = LocalDateTime.now().minusDays(days);
            LocalDateTime endTime = LocalDateTime.now();
            
            List<HealthReminder> careReminders = healthReminderService.findByUserIdAndTimeRange(userId, startTime, endTime)
                    .stream()
                    .filter(reminder -> "CARE".equals(reminder.getReminderType()) || 
                                      "TASK_COMPLETED".equals(reminder.getReminderType()))
                    .collect(Collectors.toList());
            
            return careReminders.stream()
                    .map(this::convertToHistoryRecord)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean setCarePreferences(Long userId, Map<String, Object> preferences) {
        try {
            HealthReminder prefReminder = new HealthReminder();
            prefReminder.setUserId(userId);
            prefReminder.setReminderType("CARE_PREFERENCES");
            prefReminder.setRemindTime(LocalDateTime.now());
            prefReminder.setMessage(preferences.toString());
            prefReminder.setIsCompleted(true);
            
            return healthReminderService.save(prefReminder);
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getCarePreferences(Long userId) {
        Map<String, Object> defaultPreferences = new HashMap<>();
        defaultPreferences.put("enableCareReminders", true);
        defaultPreferences.put("preferredCareTypes", Arrays.asList(CARE_TYPE_EMOTIONAL, CARE_TYPE_COMFORT));
        defaultPreferences.put("reminderFrequency", "daily");
        defaultPreferences.put("quietHours", Arrays.asList(22, 7)); // 22:00-07:00 静音
        
        return defaultPreferences;
    }
    
    @Override
    public Map<String, Object> generateCareReport(Long userId, Long partnerId, LocalDateTime startDate, LocalDateTime endDate) {
        Map<String, Object> report = new HashMap<>();
        
        try {
            List<HealthReminder> careActivities = healthReminderService.findByUserIdAndTimeRange(userId, startDate, endDate)
                    .stream()
                    .filter(reminder -> "CARE".equals(reminder.getReminderType()) || 
                                      "TASK_COMPLETED".equals(reminder.getReminderType()))
                    .collect(Collectors.toList());
            
            long totalCareActions = careActivities.size();
            long completedTasks = careActivities.stream()
                    .filter(HealthReminder::getIsCompleted)
                    .count();
            
            Map<String, Long> careTypeStats = careActivities.stream()
                    .collect(Collectors.groupingBy(
                            reminder -> extractCareType(reminder.getMessage()),
                            Collectors.counting()
                    ));
            
            report.put("period", String.format("%s 至 %s", startDate.toLocalDate(), endDate.toLocalDate()));
            report.put("totalCareActions", totalCareActions);
            report.put("completedTasks", completedTasks);
            report.put("completionRate", totalCareActions > 0 ? (double) completedTasks / totalCareActions * 100 : 0);
            report.put("careTypeDistribution", careTypeStats);
            report.put("careScore", calculateCareScore(totalCareActions, completedTasks));
            
        } catch (Exception e) {
            report.put("error", "生成关怀报告失败");
        }
        
        return report;
    }
    private String getCareTypeName(String careType) {
        switch (careType) {
            case CARE_TYPE_COMFORT: return "舒适";
            case CARE_TYPE_NUTRITION: return "营养";
            case CARE_TYPE_EXERCISE: return "运动";
            case CARE_TYPE_EMOTIONAL: return "情感";
            case CARE_TYPE_PRACTICAL: return "实用";
            default: return "关怀";
        }
    }
    
    private String getPhaseDisplayName(String phase) {
        switch (phase.toLowerCase()) {
            case "menstrual": return "月经期";
            case "follicular": return "卵泡期";
            case "ovulation": return "排卵期";
            case "luteal": return "黄体期";
            default: return "未知阶段";
        }
    }
    
    private Map<String, String> createRecommendation(String type, String title, String description) {
        Map<String, String> recommendation = new HashMap<>();
        recommendation.put("type", type);
        recommendation.put("title", title);
        recommendation.put("description", description);
        recommendation.put("icon", getCareTypeIcon(type));
        return recommendation;
    }
    
    private Map<String, Object> createCareTask(String taskId, String title, String description, String type, int priority) {
        Map<String, Object> task = new HashMap<>();
        task.put("taskId", taskId);
        task.put("title", title);
        task.put("description", description);
        task.put("type", type);
        task.put("priority", priority);
        task.put("completed", false);
        task.put("icon", getCareTypeIcon(type));
        return task;
    }
    
    private String getCareTypeIcon(String careType) {
        switch (careType) {
            case CARE_TYPE_COMFORT: return "🤗";
            case CARE_TYPE_NUTRITION: return "🍯";
            case CARE_TYPE_EXERCISE: return "🏃‍♀️";
            case CARE_TYPE_EMOTIONAL: return "💕";
            case CARE_TYPE_PRACTICAL: return "🛠️";
            default: return "❤️";
        }
    }
    
    private Map<String, Object> convertToHistoryRecord(HealthReminder reminder) {
        Map<String, Object> record = new HashMap<>();
        record.put("id", reminder.getId());
        record.put("type", reminder.getReminderType());
        record.put("message", reminder.getMessage());
        record.put("time", reminder.getRemindTime());
        record.put("completed", reminder.getIsCompleted());
        return record;
    }
    
    private String extractCareType(String message) {
        if (message.contains("舒适")) return CARE_TYPE_COMFORT;
        if (message.contains("营养")) return CARE_TYPE_NUTRITION;
        if (message.contains("运动")) return CARE_TYPE_EXERCISE;
        if (message.contains("情感")) return CARE_TYPE_EMOTIONAL;
        if (message.contains("实用")) return CARE_TYPE_PRACTICAL;
        return "其他";
    }
    
    private int calculateCareScore(long totalActions, long completedTasks) {
        if (totalActions == 0) return 0;
        double completionRate = (double) completedTasks / totalActions;
        return (int) (completionRate * 100);
    }
}
